using DevExpress.ExpressApp.Blazor.Services;
using EasyXaf.EntityDesigner.BusinessObjects.Entities.EntityProperties;
using EasyXaf.EntityDesigner.Editors.DetailViewEditors.Models;
using Microsoft.AspNetCore.Components;

namespace EasyXaf.EntityDesigner.Editors.DetailViewEditors.Components;

public partial class PropertyEditorComponent
{
    public string PropertyEditorId => $"id-{PropertyEditor.Oid}";

    [Inject]
    private IXafApplicationProvider ApplicationProvider { get; set; }

    [Parameter]
    public string CssClass { get; set; }

    [Parameter]
    public string Style { get; set; }

    [Parameter]
    public PropertyEditor PropertyEditor { get; set; }

    private string Caption
    {
        get
        {
            var caption = PropertyEditor.Caption;
            if (string.IsNullOrEmpty(caption))
            {
                caption = PropertyEditor.EntityProperty.Caption;
                if (string.IsNullOrEmpty(caption))
                {
                    caption = PropertyEditor.EntityProperty.Name;
                }
            }
            return caption;
        }
    }

    private void OnSetting()
    {
        var application = ApplicationProvider.GetApplication();
        var objectSpace = application.CreateObjectSpace(typeof(PropertyEditor));
        objectSpace.Committed += (s, e) =>
        {
            PropertyEditor.LayoutDesigner.RaiseLayoutChanged();
            InvokeAsync(StateHasChanged);
        };
        var view = application.CreateDetailView(objectSpace, PropertyEditor, true);
        application.ShowViewStrategy.ShowViewInPopupWindow(view);
    }

    private void OnDelete()
    {
        if (PropertyEditor.Parent is Panel panel)
        {
            panel.Components.Remove(PropertyEditor);
            panel.LayoutDesigner.RaiseLayoutChanged();
        }
    }

    private void OnDoubleClicked()
    {
        var application = ApplicationProvider.GetApplication();
        var objectSpace = application.CreateObjectSpace(typeof(EntityProperty));
        objectSpace.Committed += (s, e) =>
        {
            PropertyEditor.EntityProperty.Reload();
            InvokeAsync(StateHasChanged);
        };
        var entityProperty = objectSpace.GetObject(PropertyEditor.EntityProperty);
        var view = application.CreateDetailView(objectSpace, entityProperty, true);
        application.ShowViewStrategy.ShowViewInPopupWindow(view);
    }
}